package com.mxx.common.payment.wechat;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.mxx.common.conv.JsonUtil;
import com.mxx.common.payment.PrepaymentResponse;
import com.mxx.common.utils.Maps;
import com.mxx.common.utils.RandomUtil;
import com.mxx.common.utils.SignUtil;
import com.mxx.common.utils.date.DateUtil;
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class WeChatPrepaymentResponse extends PrepaymentResponse {
    /**
     * 商户号
     */
    private String appid;
    /**
     * 商户号
     */
    private String partnerid;
    /**
     * 随机字符串
     */
    private String noncestr;
    /**
     * 预支付id
     */
    private String prepayid;

    @JSONField(name = "package")
    @JsonProperty(value = "package")
    private String packageValue;

    private String timestamp;

    private String sign;


    public static WeChatPrepaymentResponse create(String prepayId, String orderId, WeChatPaymentParameter parameter) {
        WeChatPrepaymentResponse response = new WeChatPrepaymentResponse();
        response.appid = parameter.getAppId();
        response.partnerid = parameter.getMchId();
        response.prepayid = prepayId;
        response.packageValue = parameter.getPackageValue();
        response.noncestr = RandomUtil.randomCode(16);
        response.timestamp = DateUtil.nowDateTimeMilliSecond() / 1000 + "";

        String contextStr = Maps.ascii(JsonUtil.toJSON(response));
        contextStr = String.format("%s&key=%s", contextStr, parameter.getKey());
        response.sign = SignUtil.toMD5(contextStr).toUpperCase();
        response.setTradeNo(orderId);
        return response;
    }

}
